package com.czy.daishusys.ui.login;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.db.UserTable;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.ui.MainActivity;
import com.czy.daishusys.utils.GetDeviceId;
import com.czy.daishusys.utils.KeyBoardHelper;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.utils.PicDialog;
import com.czy.daishusys.utils.StatusBarUtil;
import com.czy.daishusys.widget.MyEditText;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

import static com.czy.daishusys.global.Constants.IM_IS_SHOEW_DIALOG;


public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";
    @BindView(R.id.et_mobile)
    MyEditText etMobile;
    @BindView(R.id.et_passwd)
    MyEditText etPasswd;
    @BindView(R.id.tv_forget_passwd)
    TextView tvForgetPasswd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.root_content)
    LinearLayout rootContent;

    @BindView(R.id.ll_bottom)
    View llBottom;

    private RxPermissions rxPermissions;
    private KeyBoardHelper boardHelper;
    private int bottomHeight;

    /**
     * 从其他页面跳转到登录页面（此页面）
     */
    public static void navToLogin(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {
        if (getIntent().getBooleanExtra(IM_IS_SHOEW_DIALOG, false)) {
            showLoginOutDialog("提示", "你的账号已在其他地方登录");

        }

    }

    /**
     * 退出登录提示
     */
    private void showLoginOutDialog(String title, String msg) {

        PicDialog.Builder builder = new PicDialog.Builder(LoginActivity.this);
        builder.setTitleIcon(R.mipmap.ic_dialog_title_login_out)
                .setTitle(title)
                .setMessage(msg)
                .setNegativeIcon(R.mipmap.ic_dialog_cancel)
                .setPositiveIcon(R.mipmap.ic_dialog_ensure)
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                    }
//                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        builder.create().show();
    }

    @Override
    protected void initViews() {

        StatusBarUtil.setTranslucent(this, 10);
        rxPermissions = new RxPermissions(this);

        boardHelper = new KeyBoardHelper(this);
        boardHelper.onCreate();
        boardHelper.setOnKeyBoardStatusChangeListener(onKeyBoardStatusChangeListener);
        llBottom.post(new Runnable() {
            @Override
            public void run() {
                bottomHeight = llBottom.getHeight();
            }
        });

        UserTable userTable = UserHelper.getInstance().getLastLoginUser();
        if (userTable != null) {
            if (userTable.getUserAccount() != null) {
                etMobile.setText(userTable.getUserAccount());
                etMobile.setSelection(userTable.getUserAccount().length());
            }
            if (userTable.getUserPassword() != null) {
                etPasswd.setText(userTable.getUserPassword());
                etPasswd.setSelection(userTable.getUserPassword().length());
            }
        }
    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.btn_login, R.id.tv_forget_passwd})
    public void loginOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                attemptLogin();
//                startActivity(new Intent(LoginActivity.this,UserInfoActivity.class));
                break;
            case R.id.tv_forget_passwd:
                startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
                break;
        }
    }

    private void attemptLogin() {
        etMobile.setError(null);
        etPasswd.setError(null);

        String mobile = etMobile.getText().toString().trim();
        String password = etPasswd.getText().toString();
        boolean canLogin = true;
        View focusView = null;

        //检查密码长度
        if (password.length() < 6) {
            etPasswd.setError(getString(R.string.invalid_password_length_min));
            focusView = etPasswd;
            canLogin = false;
        }

        if (password.length() > 20) {
            etPasswd.setError(getString(R.string.invalid_password_length_max));
            focusView = etPasswd;
            canLogin = false;
        }

        // 检查账号
        if (TextUtils.isEmpty(mobile)) {
            etMobile.setError(getString(R.string.invalid_account_empty));
            focusView = etMobile;
            canLogin = false;
        }

        if (canLogin) {
            getPermissions(mobile, password);
        } else {
            focusView.requestFocus();
        }
    }

    private void onLogin(final String mobile, final String passwd) {

        HttpParams params = new HttpParams();
        params.put("name", mobile);
//        params.put("password", MD5.getMD5Str(passwd));
        params.put("password", passwd);
        params.put("consoleType", "mob");
        params.put("consoleSubType", "androidAdm");
        params.put("pid",UserHelper.getInstance().getDevicePid());
        mMProgressDialog.show("登录中...");
        EasyHttp.post(Constants.URL_LOGIN)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "login error = " + e.getMessage());
                        mMProgressDialog.dismiss();
                        PhoneUtils.ShowToastMessage(LoginActivity.this, e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s) {

                        String data = PhoneUtils.checkResponseFlag(LoginActivity.this, s);
                        if (data != null) {
                            UserHelper.getInstance().saveUserAuth(mobile, passwd, true);
                            UserHelper.getInstance().saveUserInfo(LoginActivity.this, data);
                            UserHelper.getInstance().setIsLogined(true);
                            MessageHelper.getInstance().reset();
                            verifyDeviceId();
                            //环信服务器登陆
                            MyLog.d("hep", UserHelper.getInstance().getAdminInfoModel(LoginActivity.this).getImKey() + "|" + UserHelper.getInstance().getAdminInfoModel(LoginActivity.this).getImPasswd());
                            EMClient.getInstance().login(UserHelper.getInstance().getAdminInfoModel(LoginActivity.this).getImKey(), UserHelper.getInstance().getAdminInfoModel(LoginActivity.this).getImPasswd(), new EMCallBack() {//回调
                                @Override
                                public void onSuccess() {
                                    mMProgressDialog.dismiss();
                                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getNickName(),
                                            UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getUserLogo());

                                    EMClient.getInstance().groupManager().loadAllGroups();
                                    EMClient.getInstance().chatManager().loadAllConversations();

                                    MyLog.d("hep", "登录聊天服务器成功！" + UserHelper.getInstance().getAdminInfoModel(LoginActivity.this).getImKey() + "|" + UserHelper.getInstance().getAdminInfoModel(LoginActivity.this).getImPasswd());
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                }

                                @Override
                                public void onProgress(int progress, String status) {

                                }

                                @Override
                                public void onError(int code, String message) {
                                    mMProgressDialog.dismiss();
                                    MyLog.d("hep", "登录聊天服务器失败！" + code + "|" + message);
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                }
                            });
//                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                            LoginActivity.this.finish();
                        } else {
                            mMProgressDialog.dismiss();
                        }
                    }
                });
    }

    /**
     * 获取权限，待写
     */
    public void getPermissions(final String mobile, final String pass) {
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //Toast.makeText(LoginActivity.this, "权限获取成功", Toast.LENGTH_SHORT).show();
//                            GetDeviceId getDeviceId = new GetDeviceId(LoginActivity.this);
//                            String pid = getDeviceId.getCombinedId();
                            onLogin(mobile, pass);
                        } else {
                            PhoneUtils.ShowToastMessage(LoginActivity.this, "获取手机权限拒绝");
//                            showMissingPermissionDialog();
                        }
                    }
                });
    }

    // 显示缺失权限提示
    public void showMissingPermissionDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle(R.string.basic_help);
        builder.setMessage(R.string.basic_string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.basic_quit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton(R.string.basic_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.setCancelable(false);

        builder.show();
    }

    // 启动应用的设置
    public void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        boardHelper.onDestory();
        mMProgressDialog.dismiss();
    }

    private void verifyDeviceId(){
        if(UserHelper.getInstance().getDevicePid().equals("")) {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                HttpParams params = new HttpParams();
                                String pid = new GetDeviceId(LoginActivity.this).getCombinedId();
                                params.put("pid",pid);
                                EasyHttp.getInstance().addCommonParams(params);//设置全局公共参数
                                UserHelper.getInstance().setDevicePid(pid);
                            }
                        }
                    });
        }
    }

    private KeyBoardHelper.OnKeyBoardStatusChangeListener onKeyBoardStatusChangeListener = new KeyBoardHelper.OnKeyBoardStatusChangeListener() {

        @Override
        public void OnKeyBoardPop(int keyBoardheight) {

            int offset = bottomHeight - keyBoardheight;
            if(offset < 0) {
                final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) rootContent
                        .getLayoutParams();
                lp.topMargin = offset;
                rootContent.setLayoutParams(lp);
            }
        }

        @Override
        public void OnKeyBoardClose(int oldKeyBoardheight) {

            final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) rootContent
                    .getLayoutParams();
            if (lp.topMargin != 0) {
                lp.topMargin = 0;
                rootContent.setLayoutParams(lp);
            }

        }
    };
}
